//
//  BrandDisplayVC.m
//  Blank
//
//  Created by whg－54 on 15/9/23.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "BrandDisplayVC.h"
#import <AFNetworking.h>
#import <MJRefresh.h>
#import <UIImageView+WebCache.h>
#import "AFNetWorkingGet.h"
#import "LocalSave.h"
#import "BrandDisplayHeaderView.h"
#import "BrandDisplayTableViewCell.h"
#import "BrandDisplayModel.h"
#import "LocalSave.h"
#import "BrandDisplayDetailVC.h"

@interface BrandDisplayVC ()<UITableViewDelegate , UITableViewDataSource , BrandDisplayDetailVCDelegate , UISearchControllerDelegate , UISearchBarDelegate>

@property (nonatomic , strong)UITableView *brandDisplayTableView;
@property (nonatomic , strong)NSDictionary *contentDic;
@property (nonatomic , strong)NSMutableArray *letterArr;
@property (nonatomic , strong)NSMutableArray *contentArr;
@property (nonatomic , strong)BrandDisplayDetailVC *brandDetailVC;
@property (nonatomic , strong)UISearchController *searchController;
@property (nonatomic , strong)NSMutableArray *searchList;
@property (nonatomic , strong)NSMutableArray *searchResult;
@property (nonatomic , strong)UISearchBar *searchBar;
@end

@implementation BrandDisplayVC
#pragma mark - view将要出现
- (void) viewWillAppear:(BOOL)animated
{
    //self.navigationController.navigationBar.hidden = YES;
    if ([NightModel getColorModel]) {
        self.brandDisplayTableView.backgroundColor = [UIColor grayColor];
        self.brandDisplayTableView.sectionIndexBackgroundColor = [UIColor grayColor];
        self.brandDisplayTableView.sectionIndexColor = [UIColor whiteColor];
        [self.brandDisplayTableView reloadData];
    }
    else{
        
        self.brandDisplayTableView.backgroundColor = [UIColor whiteColor];
        self.brandDisplayTableView.sectionIndexBackgroundColor = nil;
        self.brandDisplayTableView.sectionIndexColor =nil;
        [self.brandDisplayTableView reloadData];
    }
    self.navigationController.navigationBar.hidden = NO;
}

#pragma mark - 重写弹出抽屉方法
- (void) openOrCloseLeftList
{
    [super openOrCloseLeftList];
    [NightModel changeAppPageCount:1];
}
 

#pragma mark - viewdidload
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"品牌";
    // Do any additional setup after loading the view.
    self.navigationController.automaticallyAdjustsScrollViewInsets = YES;
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeNightModel) name:@"nightModelChange" object:nil];
    self.brandDetailVC.delegate = self;
    self.searchList = [NSMutableArray array];
    
    
    
    [self dataHandel];
    
    
    //重设自动布局
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self tableViewSubVIews];
   // [self searchControllerSubViews];
    
    /**
     增加searchBar
     */
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44*Height)];
    [self.searchBar sizeToFit];
    self.searchBar.showsCancelButton = YES;
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"请输入品牌";
    [self.view addSubview:self.searchBar];
}

#pragma mark - 夜间模式变化重新刷新
- (void) changeNightModel
{
    if ([NightModel getColorModel]) {
        self.brandDisplayTableView.backgroundColor = [UIColor grayColor];
        self.brandDisplayTableView.sectionIndexBackgroundColor = [UIColor grayColor];
        self.brandDisplayTableView.sectionIndexColor = [UIColor whiteColor];
        [self.brandDisplayTableView reloadData];
    }
    else{
        
        self.brandDisplayTableView.backgroundColor = [UIColor whiteColor];
        self.brandDisplayTableView.sectionIndexBackgroundColor = nil;
        self.brandDisplayTableView.sectionIndexColor =nil;
        [self.brandDisplayTableView reloadData];
    }

}


#pragma mark - 初始化searchController
//- (void) searchControllerSubViews
//{
//    self.searchController=[[UISearchController alloc]initWithSearchResultsController:[[UIViewController alloc]init]];
//    self.searchController.searchBar.frame=CGRectMake(100, 10, 200, 44);
//    self.brandDisplayTableView.tableHeaderView=self.searchController.searchBar;
//    [self.searchController.searchBar sizeToFit];
//    self.searchController.searchResultsUpdater=self;
//    self.searchController.active = NO;
//    self.searchController.delegate = self;
//    self.searchController.searchBar.delegate = self;
//    
//    self.searchController.dimsBackgroundDuringPresentation=YES;
//    self.searchController.hidesNavigationBarDuringPresentation=NO;
//    self.searchController.searchBar.placeholder=@"请输入品牌";
//    //[self presentViewController:self.searchController animated:YES completion:nil];
//}
//
//- (void) updateSearchResultsForSearchController:(UISearchController *)searchController
//{
//    NSString *searchString = [NSString stringWithUTF8String:self.searchController.searchBar.text.UTF8String];
//    
//    
//    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];//用predicateWithFormat创建一个谓词，name作为键路径
//    if (self.searchResult!= nil) {
//        [self.searchResult removeAllObjects];
//    }
//    //过滤数据
//    self.searchResult= [NSMutableArray arrayWithArray:[self.searchList filteredArrayUsingPredicate:preicate]];
//    
//    for (int i = 0;i < self.searchResult.count; i++) {
//        
//        NSLog(@"%@" , self.searchResult[i]);
//    }
//    
//    [self.brandDisplayTableView reloadData];
//}

#pragma mark - 实时搜索方法
- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSString *searchString = [NSString stringWithUTF8String:self.searchBar.text.UTF8String];
    
    
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];//用predicateWithFormat创建一个谓词，name作为键路径
    if (self.searchResult!= nil) {
        [self.searchResult removeAllObjects];
    }
    //过滤数据
    self.searchResult= [NSMutableArray arrayWithArray:[self.searchList filteredArrayUsingPredicate:preicate]];
    
    for (int i = 0;i < self.searchResult.count; i++) {
        
        NSLog(@"%@" , self.searchResult[i]);
    }
    
    [self.brandDisplayTableView reloadData];

}

#pragma mark - 数据处理
- (void) dataHandel
{
    if ([LocalSave judgeFileExists:@"brandDisplayDic"]) {
        self.contentDic = [LocalSave readFile:@"brandDisplayDic"];
        self.letterArr = [[self.contentDic allKeys] mutableCopy];
        
        self.letterArr = [[self.letterArr sortedArrayUsingSelector:@selector(compare:)] mutableCopy];
        [self.brandDisplayTableView reloadData];
        
    }
    
    AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
    if (manger.reachable) {
        
        [AFNetWorkingGet GETWithAFNByURL:@"http://www.xbiao.com/app/brandlist" completion:^(id result) {
            self.contentDic = result;
            
            if (self.contentDic.allKeys.count != 0) {
                
                [LocalSave saveFile:self.contentDic fileName:@"brandDisplayDic"];
            }
            self.letterArr = [[self.contentDic allKeys] mutableCopy];
            
            self.letterArr = [[self.letterArr sortedArrayUsingSelector:@selector(compare:)] mutableCopy];
            
            /**
             *  为searchlist赋值
             */
            NSMutableArray *arr = [self.contentDic objectsForKeys:self.letterArr notFoundMarker:@"0"].mutableCopy;
            for (int i = 0; i < arr.count; i++) {
                NSArray *arr1 = arr[i];
                
                for (int j = 0; j < arr1.count; j++) {
                    NSDictionary *dic = arr1[j];
                    [self.searchList addObject:[dic objectForKey:@"name"]];
                }
                
            }

            [self.brandDisplayTableView reloadData];
        }];
    }
}

#pragma mark - 设置tableVIew
- (void) tableViewSubVIews
{
    self.brandDisplayTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44*Height, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 54*Height - 2*self.tabBarController.tabBar.frame.size.height) style:UITableViewStylePlain];
    
    self.brandDisplayTableView.separatorStyle = 0;
    self.brandDisplayTableView.delegate = self;
    self.brandDisplayTableView.dataSource = self;
    
    self.brandDisplayTableView.userInteractionEnabled = YES;
    
    [self.view addSubview:self.brandDisplayTableView];
    

}

#pragma mark - 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.searchResult.count!=0) {
        return 1;
    }
    else{
        
        return self.contentDic.allKeys.count;
    }
}

#pragma mark - footer高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

#pragma mark - header高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40*Height;
}

#pragma mark - 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80*Height;
}


#pragma mark - 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchResult.count!=0) {
        return self.searchResult.count;
    }
    else{
        NSString *letter = self.letterArr[section];
        
        self.contentArr = [self.contentDic objectForKey:letter];
        
        return self.contentArr.count;
        
    }
    
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (self.searchResult.count!=0) {
    
        return NULL;
            
    }else{
        return self.letterArr;
    }
    
}



#pragma mark - 自定义header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.searchResult.count!=0)
    {
        BrandDisplayHeaderView *header = [[BrandDisplayHeaderView alloc]initWithReuseIdentifier:@"BrandDisplayHeader"];
        return header;
    }
    else{
        
        BrandDisplayHeaderView *header = [[BrandDisplayHeaderView alloc]initWithReuseIdentifier:@"BrandDisplayHeader"];
        header.titleLabel.text = self.letterArr[section];
        
        return header;
    }
    
    
}

#pragma mark - tableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BrandDisplayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"brandDisplay"];
    if (cell == nil) {
        cell = [[BrandDisplayTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"brandDisplay"];
    }
    BrandDisplayModel *model = [[BrandDisplayModel alloc]init];
    
    /**
     *  搜索时
     */
    if (self.searchResult.count!=0) {
        NSMutableArray *arr = [self.contentDic objectsForKeys:self.letterArr notFoundMarker:@"0"].mutableCopy;
        NSMutableArray *contentDic = [NSMutableArray array];
        for (int i = 0; i < arr.count; i++) {
            NSArray *arr1 = arr[i];
            
            for (int j = 0; j < arr1.count; j++) {
                NSDictionary *dic = arr1[j];
                for (int m = 0; m < self.searchResult.count; m++) {
                    NSString *str = self.searchResult[m];
                    
                    if ([[dic objectForKey:@"name"] isEqualToString:str]) {
                        NSLog(@"%@" , str);
                        [contentDic addObject:dic];
                     }
                }
                
            }
            
        }
        NSDictionary *dic = contentDic[indexPath.row];
        
        [model setValuesForKeysWithDictionary:dic];

        
        cell.model = model;
        NSLog(@"brandid = %@" , model.name);
        //cell.brandLabel.textColor = [UIColor redColor];
        return cell;

    }
    /**
     *  不搜索时
     */
    else{
        
        self.contentArr = [self.contentDic objectForKey:self.letterArr[indexPath.section]];
        
        
        NSDictionary *dic = self.contentArr[indexPath.row];
        
        [model setValuesForKeysWithDictionary:dic];
        
        
        cell.model = model;
        return cell;
    }
}
#pragma mark - 点击searchBar搜索按钮
- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
    
    NSLog(@"%d" , self.searchController.active);
    

}

#pragma mark - 点击seacrhBar取消按钮
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}


#pragma mark - cell选中方法
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.searchBar resignFirstResponder];
    BrandDisplayTableViewCell *cell = (BrandDisplayTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    
    
    
    self.brandDetailVC = [[BrandDisplayDetailVC alloc]init];
    
    [self setBrandId:cell.brandid];

    [self.navigationController pushViewController:self.brandDetailVC animated:YES];
    
}
#pragma mark - 重写branddisplaydetail代理方法
- (void) setBrandId:(NSString *)ID
{
    self.brandDetailVC.brandId = ID;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
